package com.sc.crud;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sc.bean.PageBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.List;
import java.util.Map;

/**
 * service(业务)层的公共父类
 * @param <T> 声明泛型，被操作的具体实体对象类别
 * @param <M> 声明泛型，该泛型需要继承至指定对象类别的Mapper对象
 */
public class BaseService<T,M extends IMapper<T>> implements IService<T> {
    @Autowired(required = false)
    public M baseMapper;
    @Override
    public int insert(T entity) {
        return baseMapper.insert(entity);
    }

    @Override
    public T select(Serializable id) {
        return baseMapper.select(id);
    }

    @Override
    public int delete(Serializable id) {
        return baseMapper.delete(id);
    }

    @Override
    public int update(T entity) {
        return baseMapper.update(entity);
    }

    @Override
    public PageBean<T> queryPage(Map map) {
        /*当没有传参数，且page和pageSize参数时，默认为1和10*/
        int page = 1;
        int pageSize = 10;
        if(null != map){
            if(map.containsKey("page") && map.get("page") != null){
                page = Integer.parseInt(map.get("page").toString());
            }else {
                map.put("page",page);
            }
            if(map.containsKey("pageSize") && map.get("pageSize") != null){
                pageSize = Integer.parseInt(map.get("pageSize").toString());
            }else {
                map.put("pageSize",pageSize);
            }
        }
        /*设置分页参数*/
        //PageHelper会在执行查询之前拦截SQL，并自动添加正确的LIMIT子句
        PageHelper.startPage(page,pageSize);
        /*查询sql语句，在设置PageHelper后，查询语句中不用传入参数，且不用手动添加limit语句*/
        List entityList = baseMapper.selectPage(map);
        /*查询总条目数？*/
        PageInfo pageInfo = new PageInfo<>(entityList);
        return new PageBean(page,pageSize,(int)pageInfo.getTotal(),pageInfo.getPages(),entityList);
    }
}
